package com.showtao.front.repository;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.web.PageableDefault;

import com.showtao.front.domain.Article;
import com.showtao.front.domain.ArticleStatus;
import com.showtao.front.domain.Catalog;

public interface ArticleRepository extends JpaRepository<Article, Long> {

    @Query("select distinct a from Article a " +
    	   " left join a.catalog " +
    	   " left join a.tags")
    Page<Article> findAllLeftJoinCatalogAndTags(Pageable pageable);
    
    @Query("select distinct a from Article a " +
     	   " left join a.catalog " +
     	   " left join a.tags" +
     	   " where a.catalog = :catalog" + 
     	   "  and a.status = :status")
    Page<Article> findByCatalogLeftJoinTags(
    		 @Param("catalog") Catalog catalog,
    		 @Param("status") ArticleStatus status,
    		 Pageable pageable);
    
    long countByCatalogAndStatus(Catalog catalog, ArticleStatus status);
    
    @Query("select distinct a from Article a " +
     	   " left join a.catalog " +
     	   " left join a.tags " + 
     	   " where a.catalog = :catalog and a.status = :status")
    Article getByCatalogAndStatus(@Param("catalog") Catalog catalog, 
    		@Param("status") ArticleStatus status);
    
    @Query("select distinct a from Article a " +
      	   " left join a.catalog " +
      	   " left join a.tags " + 
      	   " where a.id = :id")
    Article getByIdLeftJoinCatalogAndTags(@Param("id") Long id);
    
    @Query("select distinct a from Article a " +
       	   " left join a.tags t" + 
       	   " where t.alias = :alias" + 
       	   " order by a.createdAt desc" )
    List<Article> getByTagAlias(@Param("alias") String alias);
        
    Page<Article> findByCatalog(Catalog catalog, 
    		@PageableDefault(page=0, size=6) Pageable pageable);
}
